package com.example.carbonbackend.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.carbonbackend.common.ErrorCode;
import com.example.carbonbackend.model.entity.User;
import com.example.carbonbackend.service.UserService;
import org.apache.commons.collections4.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.carbonbackend.constant.CommonConstant;
import com.example.carbonbackend.mapper.TradeMapper;
import com.example.carbonbackend.model.dto.trade.TradeQueryRequest;
import com.example.carbonbackend.model.entity.Trade;
import com.example.carbonbackend.model.vo.TradeVO;
import com.example.carbonbackend.service.TradeService;
import com.example.carbonbackend.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author b'j'x
 * @description 针对表【Trade(交易记录表)】的数据库操作Service实现
 * @createDate 2024-03-25 20:15:44
 */
@Service
public class TradeServiceImpl extends ServiceImpl<TradeMapper, Trade>
        implements TradeService {

    @Resource
    private UserService userService;

    /**
     * 封装查询条件
     *
     * @param tradeQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Trade> getQueryWrapper(TradeQueryRequest tradeQueryRequest) {
        QueryWrapper<Trade> queryWrapper = new QueryWrapper<>();
        if (tradeQueryRequest == null) {
            return queryWrapper;
        }
        Long id = tradeQueryRequest.getId();
        String blockchainId = tradeQueryRequest.getBlockchainId();
        Long buyerId = tradeQueryRequest.getBuyerId();
        Long sellerId = tradeQueryRequest.getSellerId();
        Long amount = tradeQueryRequest.getAmount();
        Long price = tradeQueryRequest.getPrice();
        Date startTime = tradeQueryRequest.getStartTime();
        Date endTime = tradeQueryRequest.getEndTime();

        String sortField = tradeQueryRequest.getSortField();
        String sortOrder = tradeQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.ne(ObjectUtils.isNotEmpty(blockchainId), "blockchain_id", blockchainId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(buyerId), "buyer_id", buyerId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(sellerId), "seller_id", sellerId);
        queryWrapper.eq("is_delete", false);
        queryWrapper.le(ObjectUtils.isNotEmpty(startTime), "trade_time", startTime);
        queryWrapper.ge(ObjectUtils.isNotEmpty(endTime), "trade_time", endTime);
        queryWrapper.eq(ObjectUtils.isNotEmpty(amount), "amount", amount);
        queryWrapper.eq(ObjectUtils.isNotEmpty(price), "price", price);


        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 清除敏感消息
     *
     * @param trade
     * @param request
     * @return
     */
    @Override
    public TradeVO getTradeVO(Trade trade, HttpServletRequest request) {
        if (trade == null) {
            return null;
        }

        TradeVO tradeVO = new TradeVO();
        BeanUtils.copyProperties(trade, tradeVO);

        return tradeVO;
    }

    @Override
    public Page<TradeVO> getTradeVOPage(Page<Trade> tradePage, HttpServletRequest request) {
        List<Trade> tradeList = tradePage.getRecords();
        Page<TradeVO> tradeVOPage = new Page<>(tradePage.getCurrent(), tradePage.getSize(), tradePage.getTotal());

        if (CollectionUtils.isEmpty(tradeList)) {
            return tradeVOPage;
        }
        User loginUser = userService.getLoginUser(request);

        // 1.查询关联用户信息
        User user = userService.getById(loginUser.getId());
        if(user==null){
            throw new IllegalArgumentException(String.valueOf(ErrorCode.NOT_LOGIN_ERROR));
        }
        // 2.筛选出用户本身的交易记录
        List<TradeVO> collect = tradeList.stream().map(trade -> {

            TradeVO tradeVO = new TradeVO();

            BeanUtils.copyProperties(trade,tradeVO);

            if(Objects.equals(tradeVO.getBuyerId(), loginUser.getId()))
            {
                return tradeVO;
            }

            return null;

        }).collect(Collectors.toList());

        tradeVOPage.setRecords(collect);

        return tradeVOPage;
    }
}




